﻿using UnityEditor;
using UnityEngine;

namespace CWM.Skinn
{
    public static partial class SkinnContextCommands
    {

        [CtxMenuItem("Renderer/Mesh/Vertices/Inflate/0.1", "Inflates a mesh in inches.", 0)]
        public static void RendererInflate01()
        {
            RendererInflation(0.1f.ToUnitFromStandard(ConversionUnits.Inch));
        }

        [CtxMenuItem("Renderer/Mesh/Vertices/Inflate/0.5", "Inflates a mesh in inches.", 0)]
        public static void RendererInflate05()
        {
            RendererInflation(0.5f.ToUnitFromStandard(ConversionUnits.Inch));
        }

        [CtxMenuItem("Renderer/Mesh/Vertices/Inflate/1", "Inflates a mesh in inches.", 0)]
        public static void RendererInflate1()
        {
            RendererInflation(1f.ToUnitFromStandard(ConversionUnits.Inch));
        }

        [CtxMenuItem("Renderer/Mesh/Vertices/Deflate/0.1", "Deflates a mesh in inches.", 0)]
        public static void RendererDeflate01()
        {
            RendererInflation(-0.1f.ToUnitFromStandard(ConversionUnits.Inch));
        }

        [CtxMenuItem("Renderer/Mesh/Vertices/Deflate/0.5", "Deflates a mesh in inches.", 0)]
        public static void RendererDeflate05()
        {
            RendererInflation(-0.5f.ToUnitFromStandard(ConversionUnits.Inch));
        }

        [CtxMenuItem("Renderer/Mesh/Vertices/Deflate/1", "Deflates a mesh in inches.", 0)]
        public static void RendererDeflate1()
        {
            RendererInflation(-1f.ToUnitFromStandard(ConversionUnits.Inch));
        }

        private static void RendererInflation(float nudge)
        {
            foreach (var item in SkinnContext.GetContextItems())
            {
                var context = item.GetComponent<Renderer>();
                if (SkinnEx.IsNullOrNotInAScene(context)) continue;
                if (!SkinnEx.HasMinimumRequirements(context)) continue;

                var mesh = context.GetSharedMesh().Clone() as Mesh;
                Vector3[] vertices;
                if (SkinnEx.InflateDeltas(mesh.vertices, mesh.triangles, out vertices, nudge)) { mesh.vertices = vertices; }
                SkinnContext.UndoRecord(context, "Inflate " + nudge.ToString("0.0"));
                context.SetSharedMesh(mesh);
            }
            SkinnContext.Finished();
        }
    }
}